package cn.micai.base.lambda;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * 描述：
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/6/22 10:34
 */
public class FlatMapExample {

    public static void main(String [] args) {

        String [] [] data = new String [] [] {{"a","b"},{"c","d"},{"e","f"}};

        // 1. Stream + String[] + flatMap

        // Stream<String[]>
        /*Stream<String[]> temp = Arrays.stream(data);*/

        // filter a stream of string[], and return a string[]?
        /*Stream<String[]> stream = temp.filter(x -> "a".equals(x.toString()));

        stream.forEach(System.out::println);*/


        // Stream<String>, GOOD!
        /*Stream<String> stringStream = temp.flatMap(x -> Arrays.stream(x));
        Stream<String> stringStream1 = stringStream.filter(x -> "a".equals(x.toString()));
        stringStream1.forEach(System.out::println);*/

        Stream<String> stringStream = Arrays.stream(data)
                .flatMap(x -> Arrays.stream(x))
                .filter(x -> "a".equals(x.toString()));
        stringStream.forEach(System.out::println);


        // 2. Stream + Set + flatMap

        Student student1 = new Student();
        student1.setName("mkyong");
        student1.addBook("Java 8 in Action");
        student1.addBook("Spring Boot in Action");
        student1.addBook("Effective Java (2nd Edition)");

        Student student2 = new Student();
        student2.setName("zilap");
        student2.addBook("Learning Python, 5th Edition");
        student2.addBook("Effective Java (2nd Edition)");

        List<Student> students = new ArrayList<>();
        students.add(student1);
        students.add(student2);

        List<String> collect = students.stream()
                .map(x -> x.getBook())          //Stream<Set<String>>
                .flatMap(x -> x.stream())       //Stream<String>
                .distinct()
                .collect(Collectors.toList());

        collect.forEach(x->System.out.println(x));


        // 3. Stream + Primitive + flatMapToInt

        int [] intArray = {1,2,3,4,5,6};

        // 1.Stream<int[]>
        Stream<int[]> streamArray = Stream.of(intArray);

        // 2.Stream<int[]> -> flatMap -> IntStream
        IntStream intStream = streamArray.flatMapToInt(x -> Arrays.stream(x));
        intStream.forEach(x->System.out.println(x));

    }
}
